<template>
  <el-form ref="formRef" :model="userInfo" :rules="rules" :label-width="100" style="max-width: 600px;margin-top: 2%;">
    <el-form-item label="手机号" prop="phone">
      <div style="display: flex;flex-wrap: nowrap;">
        <el-input v-model="userInfo.phone" disabled :formatter="(value) => formattingPhone(value)" />
        <el-button v-if="userInfo.phone === '未绑定'" type="primary" style="margin-left: 10%;"
          @click="openDialog('bindPhone')">绑定</el-button>
        <el-button v-else type="primary" style="margin-left: 10%;" @click="openDialog('changePhone')">更换</el-button>
      </div>
    </el-form-item>
    <el-form-item label="微信" prop="wechat">
      <div style="display: flex;flex-wrap: nowrap;">
        <el-input v-model="userInfo.wechat" disabled />
        <el-button v-if="userInfo.wechat === '未绑定'" type="primary" style="margin-left: 10%;"
          @click="openDialog('bindThird')">绑定</el-button>
        <el-button v-else type="primary" style="margin-left: 10%;" @click="openDialog('unBindThird')">解绑</el-button>
      </div>
    </el-form-item>
  </el-form>
  <!-- 弹窗 -->
  <UserInfoDialog ref="dialogRef" @success="getUserInfo" />
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import * as ProfileApi from '@/api/system/user/profile'
import UserInfoDialog from './UserInfoDialog.vue'
const message = useMessage() // 消息弹窗

defineOptions({ name: 'ResetPwd' })

const formRef = ref<FormInstance>()
const userInfo = ref({
  phone: '',
  wechat: '',
})
const rules = reactive<FormRules>({
  phone: [],
  wechat: [],
})
const getUserInfo = async () => {
  const users = await ProfileApi.getuserInfo()
  userInfo.value = users
  if (userInfo.value.phone === '') {
    userInfo.value.phone = '未绑定'
  } else {
    // userInfo.value.phone = formattingPhone(userInfo.value.phone)
  }
  const thirdInfos = await ProfileApi.getThirdInfos()
  if (thirdInfos.length === 0) {
    userInfo.value.wechat = '未绑定'
  } else {
    userInfo.value.wechat = '已绑定'
  }
}

const dialogRef = ref()
const openDialog = (type: string) => {
  if (type === 'unBindThird' && userInfo.value.phone === '未绑定') {
    message.info('请先绑定手机号')
    return
  }
  dialogRef.value.open(type, userInfo.value.phone)
}

/** 隐藏手机号 */
const formattingPhone = (cellValue) => {
  if (Number(cellValue) && String(cellValue).length === 11) {
    var mobile = String(cellValue);
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    return mobile.replace(reg, "$1****$2");
  } else {
    return cellValue;
  }
}

onMounted(async () => {
  await getUserInfo()
})
</script>
